<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;


use App\Models\RoastImages;
use App\Models\Roasts;
use App\Utils\FileUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\Validator;


class RoastController extends AuthorizedController
{

    public function create(Request $request)
    {

        $rules = [
            'roast_txt' => 'string',
            'praise_txt' => 'string',
            'images' => 'array',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->success();
        }
        $user = $request->apiUser;
        if (empty($user->mobile)){
            return $this->success();
        }

        $roast = new Roasts();
        $roast->user_id = $user->id;
        $roast->roast_txt = $request->get('roast_txt', '');
        $roast->praise_txt = $request->get('praise_txt', '');
        if (empty($roast->roast_txt) && empty($roast->praise_txt)){
            return $this->error('建议不能为空');
        }

        $roast->save();

        $images = $request->get('images', []);

        $arrImages = [];
        foreach($images as $image){
            if (!empty($image)){
                $arrImages[] = [
                    'roast_id' => $roast->id,
                    'img_url' => $image,
                ];
            }
        }
        if (count($arrImages) > 0){
           RoastImages::insert($arrImages);
        }

        return $this->success();

    }

    public function uploadImg(Request $request)
    {
        $rules = [
            'file' => 'required|file',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        $user = $request->apiUser;
        if (empty($user->mobile)){
            return $this->error('未绑定手机号！');
        }

        try{

            $file=$request->file('file');
            $fileName = 'book/roasts/' . date('Ymd') . '/' . Uuid::uuid1() . '.jpg';
            $disk = Storage::disk('oss');
            $disk->put($fileName, file_get_contents($file->getRealPath()));
            $url = FileUtil::getDomain($fileName);

            return $this->success(['img_url' => $url]);

        }catch(\Exception $e){

            return $this->error();
        }


    }


    public function index()
    {
        return $this->success([
            'banners' => Banner::getPositionBanners($this->getCity()),
            'count_down' => ExamDate::getCountDown($this->getCity()),
            'version' => env('APP_VERSION', '1.0')
        ]);
    }

    public function banner(Request $request)
    {
        $postion = $request->get('position', 0);

        return $this->success(['banners' => Banner::getPositionBanners($this->getCity())]);
    }


}
